package com.shajj.data.move;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.simpleds.bg.AbstractBackgroundTask;
import org.simpleds.bg.TaskRequest;

import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.shajj.data.Message;
import com.shajj.data.PMF;
import com.shajj.data.Record;

public class DataTask extends AbstractBackgroundTask {

	private static final Logger log = Logger.getLogger("shajj");

	private PersistenceManager persistenceManager;

	private Query pageQuery;

	private static final int PAGESIZE = 10;

	public DataTask() {
		super("shajj");

		persistenceManager = PMF.get().getPersistenceManager();
		pageQuery = persistenceManager.newQuery(Message.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected long doProceed(TaskRequest request) {
		// execute the query and locate the cursor, if any
		int start = Integer.parseInt(request.getParameter("start"));
		int processed = Integer.parseInt(request.getParameter("processed") == null ? "0" : request.getParameter("processed"));
		log.warning("Start perform thread NO." + processed);
		pageQuery.setRange(start, start + PAGESIZE);
		pageQuery.setOrdering("id asc");

		List<Message> list = (List<Message>) pageQuery.execute();
		if (list != null && list.size() > 0) {
			for (Message message : list) {
				try {
					persistenceManager.makePersistent(new Record(message.getId(), message.getValue()));
				} catch (Exception e) {
					log.severe(e.getMessage());
				}
			}

			// invoke next page
			int newStart = start + PAGESIZE;
			request.setParameter("start", String.valueOf(newStart));
			request.setParameter("processed", String.valueOf(processed + list.size()));
			defer(request);
		} else {
			notifyFinalization();
		}
		return processed;
	}

	private void defer(TaskRequest request) {
		TaskOptions url = TaskOptions.Builder.withUrl(request.getUri());
		for (String paramName : request.getParameterNames()) {
			url.param(paramName, request.getParameter(paramName));
		}
		QueueFactory.getDefaultQueue().add(url);
	}

}
